package org.jz.gae.redbook.spb.server.controller;

import java.util.HashMap;
import java.util.Map;

import org.jz.gae.redbook.spb.server.cache.LocationCashe;
import org.jz.gae.redbook.spb.shared.LocationEntityView;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class LocationCasheGoogle implements LocationCashe
{
	private static LocationCashe instance;
	
	public synchronized static LocationCashe getInstance()
	{
		if (instance == null)
		{
			instance = new LocationCasheGoogle();
		}
		return instance;
	}
	
	private Map<Key, LocationEntityView> cashe = new HashMap<Key, LocationEntityView>();

	@Override
	public synchronized LocationEntityView getLocationEntityView(String _LocationKey)
	{
		Key locationKey = KeyFactory.stringToKey(_LocationKey);
		LocationEntityView result = cashe.get(locationKey);
		if (result == null)
		{
			try
			{
			    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	            Entity location = datastore.get(locationKey);
	            result = new LocationEntityView();
	            LocationUtils.reflectEntityToView(location, result);
	            cashe.put(locationKey, result);
	            return result;
			}
			catch(EntityNotFoundException ex)
			{
				return null;
			}
		}
		else
		{
		    return result;
		}
	}

}
